package com.buptcoder.wifimap;

import java.util.List;

import org.json.JSONArray;

import com.buptcoder.wifimap.Utils.MapLog;
import com.buptcoder.wifimap.location.Locator;
import com.buptcoder.wifimap.wifiinfo.WifiAccessPointInfo;
import com.buptcoder.wifimap.wifiinfo.WifiLocationInfoGetter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MapActivity extends Activity implements
        Locator.OnLocationChangedListener, View.OnClickListener {

    private static final String TAG = "MapActivity";
    private static final int LOADING_COMPLETE = 1;

    private WebView mMapView;
    private List<WifiAccessPointInfo> mApInfoList;
    private Handler mUIHandler;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        mContext = this;
        setContentView(R.layout.map_view);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                R.layout.titlebar_with_back);
        setTitle();
        initWebandWebSettings();
        mMapView.loadUrl("file:///android_asset/map.html");
        initiateHandler();
        loadApInfoData();
    }

    private void setTitle() {
        TextView textView = (TextView) findViewById(R.id.titlebar_title);
        textView.setText(R.string.string_map_view_title);
        Button button = (Button) findViewById(R.id.titlebar_back_btn);
        button.setOnClickListener(this);
    }

    private void initWebandWebSettings() {
        mMapView = (WebView) this.findViewById(R.id.map_view);
        mMapView.setWebChromeClient(new MyWebChromeClient());
        WebSettings webSettings = mMapView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        addJavaScriptInterfaces();
    }

    private void addJavaScriptInterfaces() {
        // addJavaScriptInterfaceOfDevInfo();
        // addJavaScriptInterfaceOfConfiguration();
        addLocatorObject();
    }

    private void addLocatorObject() {
        Locator locator = Locator.getInstance(this.getApplicationContext());
        locator.addLocationChangeListener(this);
        mMapView.addJavascriptInterface(locator, "locator");
    }

    private void initiateHandler() {
        mUIHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                if (message.what == LOADING_COMPLETE) {
                    MapLog.d(TAG, "Loading complete!");
                    addAdapterObject();
                    mMapView.reload();
                }
            }
        };
    }

    private void addAdapterObject() {
        ApInfoAdapter adapter = new ApInfoAdapter();
        mMapView.addJavascriptInterface(adapter, "apadapter");
    }

    private void loadApInfoData() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                WifiLocationInfoGetter getter = WifiLocationInfoGetter
                        .getInstance(mContext);
                mApInfoList = getter.getAllAPInfo();
                mUIHandler.sendEmptyMessage(LOADING_COMPLETE);
            }

        }).start();
    }

    // For debug
    class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                JsResult result) {

            Toast.makeText(MapActivity.this, message, Toast.LENGTH_SHORT)
                    .show();
            MapLog.d(TAG, "Error happened: " + message);
            return false;
        }
    }

    @Override
    public void onLocationChanged() {
        addLocatorObject();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.titlebar_back_btn) {
            onBackPressed();
        }
    }

    class ApInfoAdapter {
        public String getAllApInfo() {
            JSONArray result = new JSONArray();
            if (mApInfoList != null) {
                for (WifiAccessPointInfo info : mApInfoList) {
                    result.put(info.toJSON());
                }
            }
            return result.toString();
        }
    }
}
